package com.shiguiwu.springmybatis.data.ldap;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.ldap.LdapProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: config
 * @author: stone
 * @date: Created by 2022/7/16 17:08
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.ldap
 */
@Configuration
@ConditionalOnProperty(prefix = "spring.ldap",name = "disable",havingValue = "true")
public class LdapConfig {


    private LdapTemplate ldapTemplate;


    @Bean
    public LdapContextSource contextSource(LdapProperties properties) {
        LdapContextSource contextSource = new LdapContextSource();
        Map<String, Object> config = new HashMap<>();
        contextSource.setUrls(properties.getUrls());
        contextSource.setBase(properties.getBase());
        contextSource.setUserDn(properties.getUsername());
        contextSource.setPassword(properties.getPassword());
        //  解决乱码
        config.put("java.naming.ldap.attributes.binary", "objectGUID");

        contextSource.setPooled(true);
        contextSource.setBaseEnvironmentProperties(config);
        return contextSource;
    }

    @Bean
    public LdapTemplate ldapTemplate(LdapProperties properties) {
        if (null == ldapTemplate) {
            ldapTemplate = new LdapTemplate(contextSource(properties));
        }
        return ldapTemplate;
    }


}
